import Message from './Message';
import MsgCodec from './MsgCodec';
import MessageType from './MessageType';
import MessageCommand from './MessageCommand';
import UuidGenerator from './UuidGenerator';
import MessageBody from './MessageBody';
const WebSocket = require("ws")
interface OnMessageImpl {
    (data:any):void;
}
interface OnCloseImpl {
    (event: any): void;
}

class SocketBus {
    public _id!:string;
    public ws!:WebSocket;
    public websocketAddr : string;

    public onClose!: OnCloseImpl; 
    public onMsg!:OnMessageImpl;
    public wsPath!:string;
    private closed!:boolean;
    private timer!:any;
    public onConnect!:any;
    constructor(websocketAddr:string){
        this.closed = false;
        this.websocketAddr = websocketAddr  
        this._id = "SocketBus-"+UuidGenerator.generate()+"."+websocketAddr;      
        let self = this;    
        self.onConnect = ()=>{};
        self.timer = setInterval(()=>{
            self.pingpong();
            },3000);   

        
    }


    public pingpong(){
        let messagePingPong:Message = {
            type:MessageType.Command,
            command:MessageCommand.PINGPONG,
            uuid:UuidGenerator.generate(),
            body:new MessageBody("")
        }
        this.send(messagePingPong);
    }
    public send(data:Message){
        try{
            this.ws.send(MsgCodec.encode(data))
        }catch(e){
            if(this.ws.readyState!=1){
                console.debug("got exception :");
                console.debug(e);
                this.connect();
            }
        }
    }
    public connect(){
       
        let self = this;
        if(self.closed){
            return;
        }
        if(self.ws && self.ws.readyState==1){
            console.debug("already  connected:"+self._id);
            return;
        }
        if(self.ws && self.ws.readyState==0){
            console.debug("already connection..."+self._id);
            return;
        }
        console.debug("connecting");
        self.ws = new WebSocket(this.websocketAddr);
        self.ws.onopen=function(){
            console.debug("... connected!"+self._id);
            self.onConnect();
        };
        self.ws.onclose = function (evt:any) {
            console.debug("ws closed:"+self._id);
            self.connect();
        };
        self.ws.onmessage = function (evt:any) {
            //console.log("new msg:");
            //console.log(evt);  
            console.debug("got msg of :"+self._id);
            self.onMsg(evt.data);
        };
        //self.ws.onclose = self.onClose;
    }
    public close(){        
        this.closed = true; 
        clearInterval(this.timer);   
        this.ws.close();  
         
    }
}
export default SocketBus;
